package com.cn.lcc.base.exception;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerExceptionResolverComposite;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.cn.lcc.util.request.ContextManager;
import com.cn.lcc.util.request.RequestContextUtil;
/**
 * @author lcc  
 * @date 2017年6月13日
 * @备注   统一异常处理
 */
public class ExceptionResolver extends HandlerExceptionResolverComposite {

    private static final Logger logger = LoggerFactory
            .getLogger(ExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception exception) {
        if (RequestContextUtil.getContext() != null) {
            RequestContextUtil.getContext().put("sign",
                    request.getParameter("sign"));
        }
        Map<String, Object> model = new HashMap<String, Object>();
        if (exception instanceof BaseException) {
            logger.error("{}, uri=[{}], parameters=[{}]",
                    exception.getMessage(), RequestContextUtil.getUri(),
                    RequestContextUtil.getContext());
            BaseException baseException=(BaseException)exception ;
            model.put("code", baseException.getCode());
        } else {
            logger.error("{}, uri=[{}], parameters=[{}]",
                    exception.getMessage(), RequestContextUtil.getUri(),
                    RequestContextUtil.getContext(), exception);
        }
        model.put("success", false);
        model.put("message", exception.getMessage());
        model.put("data", null);
        ContextManager.clearAll(); // 抛错的话，原先拦截器的退出处理会失效，所以这里再全部执行一遍
        return new ModelAndView(new MappingJackson2JsonView(), model);
    }
}
